// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const _ = db.command;
const BASE = 'cloud-user-base';
const timeutil = require('./timeutil');
const ACTS = 'cloud-activities'
const SWIPER = 'cloud-activities-swiper';
const GROUP = 'cloud-activities-groups';
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let openid = wxContext.OPENID;
  /**查询当前日期的活动 */
  let nowTime = timeutil.TimeCode();
  let activityRes = await db.collection(ACTS).where({
    startTime: _.lte(nowTime),
    endTime: _.gte(nowTime)
  }).get();
  /**获取符合日期条件全部活动列表 */
  let activities = activityRes.data;
  let nowActivity = {};
  if (activities.length == 0) {
    return {
      errCode: -1,
      errMsg: '当前日期暂无活动'
    }
  } else {
    /**选择第一个赋值 */
    nowActivity = activities[0];
  }
  /**新增曝光次数 */
  db.collection(ACTS).doc(nowActivity._id).update({
    data: {
      exposeNum: _.inc(1)
    }
  })
  /**根据活动查询活动SWIPER */
  let activityId = nowActivity._id;
  let swiperRes = await db.collection(SWIPER).where({
    activityId
  }).get();
  let swipers = swiperRes.data;
  if (swipers.length == 0) {
    return {
      errCode: -1,
      errMsg: '请在后台配置至少一个SWIPER'
    }
  }
  /**根据活动查询组别 */
  let groupRes = await db.collection(GROUP).where({
    activityId
  }).get();
  let groups = groupRes.data;
  if (groups.length == 0) {
    return {
      errCode: -1,
      errMsg: '请在后台配置至少一个分组'
    }
  }
  let userInfo = null
  /*查询用户是否存在 */
  let userRes = await db.collection(BASE).where({
    openid
  }).get();
  if (userRes.data.length == 0) {
    userInfo = null
  }else{
  userInfo = userRes.data[0];
  }
  /**返回项目配置列表 */
  return {
    errCode: 0,
    errMsg: 'config-auth:ok',
    activity: nowActivity,
    swiperList: swipers,
    groupList: groups,
    openid: openid,
    userInfo
  }
}